package com.reliable.service.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reliable.api.dto.ReliableTaskStatDTO;
import com.reliable.api.dto.user.ReliableUserLite;
import com.reliable.api.param.IdParam;
import com.reliable.api.param.PageParam;
import com.reliable.api.param.task.ReliableTaskPageParam;
import com.reliable.api.param.task.ReliableTaskSaveParam;
import com.reliable.api.param.task.ReliableTaskUpdateParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.common.core.page.TableDataInfo;
import com.reliable.common.utils.DateUtils;
import com.reliable.common.utils.StringUtils;
import com.reliable.framework.utils.JwtUtils;
import com.reliable.service.domain.ReliabUploadRecord;
import com.reliable.service.service.ChatMessageService;
import com.reliable.service.domain.ReliableTransactionRecord;
import com.reliable.service.utils.IdEncryptUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.reliable.service.domain.ReliableTask;
import com.reliable.service.service.IReliableTaskService;

/**
 * 任务Controller
 * 
 * @author ruoyi
 * @date 2025-07-09
 */
@RestController
@RequestMapping("/reliable/task")
@Api(value = "任务控制器", tags = {"任务管理"})
public class ReliableTaskController {

    @Autowired
    private IReliableTaskService reliableTaskService;

    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 查询任务列表
     */
    @ApiOperation("查询任务列表")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody PageParam param) {
        LambdaQueryWrapper<ReliableTask> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneEmpty(param.getTaskName())){
            wrapper.like(ReliableTask::getTaskName, param.getTaskName());
        }
        IPage<ReliableTask> page = reliableTaskService.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        List<ReliableTask> records = page.getRecords();

        // 提取任务ID列表
        List<Long> taskIds = records.stream().map(ReliableTask::getId).collect(Collectors.toList());

        // 批量获取统计信息
        List<ReliableTaskStatDTO> statDTOs = new ArrayList<>();
        if (!taskIds.isEmpty()) {
        //    List<ReliableTaskStatDTO> batchStats = chatMessageService.getTaskStatisticsBatch(taskIds);
          //  Map<Long, ReliableTaskStatDTO> statsMap = batchStats.stream()
                    //.collect(Collectors.toMap(ReliableTaskStatDTO::getTaskId, Function.identity()));

            // 修复点：将 .toList() 改为 .collect(Collectors.toList())
            statDTOs = records.stream().map(task -> {
                ReliableTaskStatDTO statDTO = new ReliableTaskStatDTO();

                // 基本信息
                statDTO.setBusinessId(IdEncryptUtils.encrypt(task.getId()));
                statDTO.setTaskName(task.getTaskName());
                statDTO.setCreateTime(task.getCreateTime());
                statDTO.setStatus(task.getStatus());
                statDTO.setLocation(task.getAddressName());
                statDTO.setDescription(task.getTaskDescription());

                // 统计信息
                ReliableTaskStatDTO stats = new ReliableTaskStatDTO();
                statDTO.setTaskId(stats.getTaskId()); // 添加这一行确保taskId被设置
                statDTO.setSessionCount(692899L);
                statDTO.setEntCount(11111L);
                statDTO.setMessageCount(10193035L);
                statDTO.setIpCount(7423432L);
                statDTO.setVisitorIpCount(7423432L);
                statDTO.setReferrerUrlCount(7423432L);
                statDTO.setPageUrlCount(6423432L);
                //statDTO.setEarliestTime(2025-05-03 22:43:34+08);
                statDTO.setLatestTime(stats.getLatestTime());
                statDTO.setUrlCount(stats.getPageUrlCount());

                return statDTO;
            }).collect(Collectors.toList()); // ✅ 修复 here
        }

        TableDataInfo data = new TableDataInfo(statDTOs, (int) page.getTotal());
        return AjaxResult.success(data);
    }

    /**
     * 获取任务详细信息
     */
    @ApiOperation("获取任务详细信息")
    @PostMapping(value = "/info")
    public AjaxResult getInfo(@RequestBody IdParam param) {
        ReliableTask task = reliableTaskService.getById(IdEncryptUtils.decrypt(param.getBusinessId()));
        return AjaxResult.success(task);
    }

    /**
     * 新增任务
     */
    @ApiOperation("新增任务")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ReliableTaskSaveParam param) {
        ReliableTask reliableTask = new ReliableTask();
        BeanUtils.copyProperties(param, reliableTask);
        ReliableUserLite user = JwtUtils.getCurrentUser();
        Long id = user.getId();
        reliableTask.setCreateBy(id);
        reliableTask.setCreateTime(DateUtils.getBeijingDate());
        return toAjax(reliableTaskService.save(reliableTask));
    }

    /**
     * 修改任务
     */
    @ApiOperation("修改任务")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody ReliableTaskUpdateParam param) {
        LambdaUpdateWrapper<ReliableTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ReliableTask::getId,IdEncryptUtils.decrypt(param.getBusinessId()));
        if (StringUtils.isNotEmpty(param.getTaskName())){
            updateWrapper.set(ReliableTask::getTaskName, param.getTaskName());
        }
        if (StringUtils.isNotEmpty(param.getTaskDescription())){
            updateWrapper.set(ReliableTask::getTaskDescription, param.getTaskDescription());
        }
        if (StringUtils.isNotEmpty(param.getAddressName())){
            updateWrapper.set(ReliableTask::getAddressName, param.getAddressName());
        }
        updateWrapper.set(ReliableTask::getUpdateTime, DateUtils.getBeijingDate());
        ReliableUserLite user = JwtUtils.getCurrentUser();
        ReliableTask reliableTask = new ReliableTask();
        Long id = user.getId();
        BeanUtils.copyProperties(param, reliableTask);
        reliableTask.setUpdateBy(id);
        reliableTask.setUpdateTime(DateUtils.getBeijingDate());
        return toAjax(reliableTaskService.update(updateWrapper));
    }

    /**
     * 删除任务
     */
    @ApiOperation("删除任务")
    @PostMapping("/delete")
    public AjaxResult remove(@RequestBody IdParam param) {
        return toAjax(reliableTaskService.removeById(IdEncryptUtils.decrypt(param.getBusinessId())));
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean rows) {
        return rows ? AjaxResult.success() : AjaxResult.error();
    }
}